import { Component } from 'react'
import Taro from '@tarojs/taro'
import { View, Text, Image } from '@tarojs/components'
import homeIcon from '../assets/tabbar/home.png'
import creationIcon from '../assets/tabbar/creation.png'
import mineIcon from '../assets/tabbar/mine.png'
import { TabContext } from '../context'

import './index.scss'

const tabList = [
  {
    pagePath: '/pages/home/index',
    selectedIconPath: homeIcon,
    iconPath: homeIcon,
    text: '首页'
  },
  {
    pagePath: '/pages/creation/index',
    selectedIconPath: creationIcon,
    iconPath: creationIcon,
    text: '创作'
  },
  {
    pagePath: '/pages/mine/index',
    selectedIconPath: mineIcon,
    iconPath: mineIcon,
    text: '我的'
  },
]

export default class Index extends Component {
  static contextType = TabContext;
  state = {
    color: 'rgba(255,255,255,0.3)',
    selectedColor: '#ffffff',
  }

  switchTab = (index, url) => {
    this.context.setTabIndex(index)
    Taro.switchTab({ url })
  }

  renderTabBarItem = (item, index) => {
    const { color, selectedColor } = this.state
    const { tabIndex } = this.context;
    return (
      <View key={item.text} className={`tab-bar-item ${index === 1 ? 'active' : ''}`} onClick={() => this.switchTab(index, item.pagePath)}>
        <Image src={item.selectedIconPath} />
        <Text className="tab-bar-text" style={{ color: tabIndex === index ? selectedColor : color }}>{item.text}</Text>
      </View>
    )
  }

  render() {
    return (
      <View className='tab-bar'>
        {tabList.map(this.renderTabBarItem)}
      </View>
    )
  }
}
